#ifndef __COMM_HPP__
#define __COMM_HPP__

#include<iostream>
#include<cerrno>
#include<cstdio>
#include<cstring>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<cassert>
using namespace std;
#define PATHNAME "."
#define PROJID 0x6666

const int gsize=4096;
key_t getkey()
{
    key_t k=ftok(PATHNAME,PROJID);
    if(k==-1)
    {
        cerr<<errno<<" : "<<strerror(errno)<<endl;
        exit(1);
    }
    return k;
}

string toHex(int x)
{
    char buffer[64];
    snprintf(buffer,sizeof buffer,"0x%x",x);
    return buffer;
}

int createShm(key_t k,int size)//server
{
    umask(0);
    int shmid= shmget(k,size,IPC_CREAT | IPC_EXCL|0666);
    if(shmid==-1)
    {
        cerr<<errno<<" : "<<strerror(errno)<<endl;
        exit(2);
    }
    return shmid;
}

int getShm(key_t k,int size)//client
{
    int shmid=shmget(k,size,IPC_CREAT);
    if(shmid==-1)
    {
        cerr<<errno<<" : "<<strerror(errno)<<endl;
        exit(2);
    }
    return shmid;
}

void delShm(int shmid)
{
    int n=shmctl(shmid,IPC_RMID,nullptr);
    assert(n!=-1);
    (void)n;
}

char* attachShm(int shmid)
{
    char *start=(char*)shmat(shmid,nullptr,0);
    return start;
}

void detachShm(char*start)
{
    int n=shmdt(start);
    assert(n!=-1);
    (void)n;
}

#define SERVER 0
#define CLIENT 1

class Init
{
public:
    Init(int flag):_flag(flag)
    {
        _key =getkey();
        if(flag==SERVER)
            shmid=createShm(_key,gsize);
        else if(flag==CLIENT)
            shmid=getShm(_key,gsize);
        else
            cout<<"通信错误"<<endl;
        start=attachShm(shmid);
        
    }
    char* Getstart()
    {
        return start;
    }
    ~Init()
    {
        detachShm(start);
        if(_flag==SERVER)
            delShm(shmid);
    }
private:
    key_t _key;
    int shmid;
    int _flag;
    char*start;
};

#endif